package com.mkx.multitier;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 抽象层次类，提供Layer接口的通用实现
 */
public abstract class AbstractLayer implements Layer {
    protected final String layerName;
    protected final AtomicBoolean initialized = new AtomicBoolean(false);
    protected final AtomicBoolean started = new AtomicBoolean(false);
    protected final Monitor monitor;
    
    public AbstractLayer(String layerName, Monitor monitor) {
        this.layerName = layerName;
        this.monitor = monitor;
    }
    
    @Override
    public void initialize() {
        if (initialized.compareAndSet(false, true)) {
            doInitialize();
            if (monitor != null) {
                monitor.onLayerInitialized(layerName);
            }
        }
    }
    
    @Override
    public void start() {
        if (initialized.get() && started.compareAndSet(false, true)) {
            doStart();
            if (monitor != null) {
                monitor.onLayerStarted(layerName);
            }
        }
    }
    
    @Override
    public void shutdown() {
        if (started.compareAndSet(true, false)) {
            doShutdown();
            if (monitor != null) {
                monitor.onLayerShutdown(layerName);
            }
        }
    }
    
    @Override
    public String getLayerName() {
        return layerName;
    }
    
    @Override
    public void processTask(Task task) {
        if (!started.get()) {
            throw new IllegalStateException("Layer " + layerName + " is not started");
        }
        
        long startTime = System.currentTimeMillis();
        try {
            doProcessTask(task);
            if (monitor != null) {
                monitor.onTaskProcessed(layerName, task, System.currentTimeMillis() - startTime);
            }
        } catch (Exception e) {
            if (monitor != null) {
                monitor.onTaskFailed(layerName, task, e, System.currentTimeMillis() - startTime);
            }
            throw e;
        }
    }
    
    /**
     * 具体的初始化逻辑，由子类实现
     */
    protected abstract void doInitialize();
    
    /**
     * 具体的启动逻辑，由子类实现
     */
    protected abstract void doStart();
    
    /**
     * 具体的关闭逻辑，由子类实现
     */
    protected abstract void doShutdown();
    
    /**
     * 具体的任务处理逻辑，由子类实现
     */
    protected abstract void doProcessTask(Task task);
}
